package dabs.engine.plant;

import dabs.engine.control.ComponentCommand;
import dabs.engine.environment.AcceptsModifier;
import dabs.engine.environment.Modifier;
import dabs.engine.environment.TemporaryDisable;
import dabs.engine.messaging.Notification;
import dabs.engine.messaging.NotificationHandler;

public class Pump extends ComponentPart implements AcceptsModifier{
	private static final long serialVersionUID = 7244797591801230882L;
	
	private int flowAmount;
	private int saveFlow = 0;
	
	public Pump(NotificationHandler mailBox, String name, int capacity, int outRate) {
		super(mailBox, name, capacity, outRate);
		flowAmount = 15;
	}
	
	public int getFlowAmount() {
		return flowAmount;
	}
	
	public void setFlowAmount( int flowAmount ) { 
		if ( isDeactivated() == false ) {
			this.flowAmount = flowAmount;
			passMessage(new Notification(getName(), "Speed set to " + flowAmount + "%."));
		} 
		else { 
			passMessage( new Notification(getName(), "Pump is stalled") );
		}
	}
	
	@Override
	protected void receiveModifier(Modifier modifier) {
		super.receiveModifier(modifier);
		if (modifier instanceof TemporaryDisable) {
			saveFlow = flowAmount;
			flowAmount = 0;
		} else { 
			throw new RuntimeException("wtf is this modifier? " + modifier.getClass().getName());
		}
	}
	
	@Override
	protected void inactivatedModifier(Modifier modifier) {
		super.inactivatedModifier(modifier);
		if (modifier instanceof TemporaryDisable) {
			passMessage(new Notification(getName(), "is now active again"));
			flowAmount = saveFlow;
		}
	}
	
	@Override
	public void tick() {
		getNewHydroState().sendToNext(getHydroProp().getOutRate() + flowAmount, true, getOutputs(), getPressure());
		//Lose health if running at more than 80% capacity equal to percentage over 80%
		if (getFlowAmount() > 80) {
			setHealth(getHealth() - (getFlowAmount() - 80));
		}
		super.tick();
	}
	
	@Override
	public void runCommand(ComponentCommand command) {
		assert(command.getDestination().equals(getName()));
		try{
			int newSpeed = Integer.parseInt(command.getArguments().get(0)); //Line to be changed depending on arguments.
			if (newSpeed <= 100 && newSpeed >= 0){
			setFlowAmount(newSpeed);
			}
			else{
			passMessage(new Notification(getName(), "Speed  must be set to a value between 0 and 100"));
			}
		}
		catch (java.lang.NumberFormatException e){
			passMessage(new Notification(getName(), "Rods must be set to an integer value."));
				return;
		}
	}
	
	@Override
	public String read() {
		return String.format("%s\tPumping speed: %d%%\n", super.read(), getFlowAmount());
	}
	
}
